package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.cache.service.ISecurityRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.util.JsonResult;
import cn.wolfcode.luowowo.util.RequestUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.logging.Handler;

/**
 * 防刷拦截器
 */
public class BrushProofInterceptor  implements HandlerInterceptor {

    @Autowired
    private ISecurityRedisService securityRedisService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //防刷验证
        //uri 与 url  区别
        String uri = request.getRequestURI().substring(1);
        String ip = RequestUtil.getIPAddress();
        String key = RedisKeys.BRUSH_PROOF.join(uri, ip);
        if(!securityRedisService.isAllowBrush(key)){
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.error(500,"请勿频繁访问","谢谢")));
            return false;
        }
        return true;
    }
}
